package common.web.action;

import java.text.MessageFormat;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import common.log.util.LogModule;
import common.log.util.LogType;
import common.log.vo.WebLog;
import common.rbac.po.User;
import common.security.web.util.SecurityUtil;
import common.web.vo.Result;

@SuppressWarnings("deprecation")
@Controller
@RequestMapping()
public class ChangePWDAction extends CommonAction {
	
	@Autowired(required=false)
	PasswordEncoder encoder;
	

	@RequestMapping("/changePWD")
	@ResponseBody
	public Result save(@RequestBody JSONObject json) {
		String pwd = json.getString("password");
		String userId = SecurityUtil.getUserId();
		User user = this.baseService.load(User.class, userId);
		if (null != user) {
			WebLog log = new WebLog(LogModule.USER, LogType.UPDATE, "修改密码失败");
			try {
				if(null != encoder) {
					pwd = encoder.encodePassword(pwd, null);
				}
				user.setPassword(pwd);
				this.baseService.update(user);
				log.setSuccess(MessageFormat.format("用户[{0}],修改密码成功!", user.getName()));
			} catch (Exception e) {
				log.setFail(MessageFormat.format("用户[{0}],修改密码失败!", user.getName()));
				logger.error("", e);
				return Result.fail("数据错误，请刷新后重试");
			} finally {
				super.saveLog(log);
			}
		} else {
			return Result.fail("数据错误，请刷新后重试");
		}
		return Result.SUCCESS;
	}
}
